package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WifiEAPManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class PeapWidget extends GeneralTestWidget {

    private WlanManager wlanManager;
    private WlanManager wlanManager2;
    private WifiEAPManager wEapManager;
    private Handler handler;
    private Activity ctx;
    private LinearLayout l;
    private ScrollView sv;
    private LinearLayout chartLayout;
    private static final String TAG = "ApRelevanceTest";
    private Button backBtn;
    private Button btnRetest;
    private boolean connecting; 
    private int current = 0;
    private int timeout_num;
    private int timeFail_num;
    private int timeDisFail_num;
    private int frequency = 4;
    private float totalTime;
    private float totalDisTime;
    private double[] xdata;
    private double[] ydata;
    private double lydata[];
    private double oydata[];
    private Task task;
    private String fileName;
    private ScanResult scan;
    private long startTime;
    private long endTime; 
    private LinearLayout ll;
    private TextView tv_peap;
    private ProgressBar pb;
    
    /**
     * PEAP认证下线
     * <br>1: PEAP认证
     * <br>2: PEAP下线
     * <br>0: 
     */
    private int isTestPeapConnect = 0;
    
    public PeapWidget(Activity context) {
        super(context);
        inflate(context, R.layout.peap_test_widget, this);
        this.ctx = context;
        l = (LinearLayout) this.findViewById(R.id.peapauth_test_layout);
        sv = (ScrollView) findViewById(R.id.peap_test_ScrView);
        chartLayout = (LinearLayout) findViewById(R.id.peapTestChartLayout);
        backBtn = (Button) findViewById(R.id.peap_test_btnback);
        ll = (LinearLayout)findViewById(R.id.linearlaout_peap);
        tv_peap = (TextView)findViewById(R.id.peap_test);
        pb = (ProgressBar)findViewById(R.id.peap_progress);
        pb.setMax(frequency);
     //   btnRetest = (Button) findViewById(R.id.btn_retest);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	switch(GlobalApp.nowNetType) {
				case 1:
					backToTestWidget_Wlan(ctx);
					break;
				case 2:
					backToTestWidget_TD(ctx);
					break;
				case 3:
					backToTestWidget_GSM(ctx);
					break;
				default:
					break;
				}
            }
        });

       /* btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // ApRelevanceTestWidget aw = new ApRelevanceTestWidget(ctx);
                // ctx.setContentView(aw);
                // aw.scanWifi();
                if (null != fileName) {
                //    new UploadResultTask().execute();            ////////////////////////////
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
            }
        });*/
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    dismissMessageDialog();
                    showCMCCAUTOScanDialog(ctx, wlanManager, handler);
                    wlanManager.stopScan(); 
                    break; 
                case MessageWhat.PEAP_INPUT_AUTHINFO:
                    inputUserPassDialog(wlanManager, handler);
                    break;
                case MessageWhat.WIFI_SELECTED: 
                    start(scan);
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissMessageDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                default:
                	if(current < frequency+1) {
                		update(msg.what);
                	}
                }
            }
        };
        wlanManager2 = new WlanManager(ctx);
        wlanManager = new WlanManager(ctx);
        wlanManager2.setHandler(handler);  
        wlanManager.setHandler(handler);  
        task = new Task();
    } 

    protected void scanWifi() {
        showMessageDialog(ctx, "正在扫描CMCC-AUTO网络...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    private final class PeapTestThread extends Thread { 
    	private ScanResult scanResult; 
        public PeapTestThread(ScanResult scanResult) { 
        	this.scanResult = scanResult;
        }
        @Override
        public void run() {
        	executable = true;
        	isTestPeapConnect = 1;
            while (current < frequency+1 && executable) {
                 
            	if (!connecting) {
	                 connecting = true;  
	                 if(current < frequency) {
	                	 if(isTestPeapConnect == 1) {
		                	 current++;
		                	 try {
			            		 peapConnectTimerTask.cancel();
			                 } catch(Exception e){}
			                 startConnectTimeoutListener();
		                     wlanManager.connectPEAP(scanResult);
		                 } else if(isTestPeapConnect == 2) {
		                	 try {
			            		 peapDisconnectTimerTask.cancel();
			                 } catch(Exception e){}
			                 startDisconnectTimeoutListener();
			                 wlanManager2.disConnectPEAP(scanResult);
		                 }
	                 } else {
	                	 try {
		            		 peapDisconnectTimerTask.cancel();
		                 } catch(Exception e){}
		                 startDisconnectTimeoutListener();
		                 wlanManager2.disConnectPEAP(scanResult);
	                 }
	                 
	                 
	                 
                    /*if(current == frequency+1 && wlanManager2.currentNetWorkStatus(WlanManager.SSID_CMCC_AUTO) == 0)
                 	{ 
                    	wlanManager2.disConnectPEAP(scanResult);
                 	}
            		if(current < frequency+1 ) { 
		            	 if(current !=1 && wlanManager2.currentNetWorkStatus(WlanManager.SSID_CMCC_AUTO) == 0){
		                   	wlanManager2.disConnectPEAP(scanResult);
		                  }
		            	 try {
		            		 peapConnectTimerTask.cancel();
		                 } catch(Exception e){}
	                     wlanManager.connectPEAP(scanResult);
	                     startConnectTimeoutListener();
                 	}*/
                }
            	try {
					Thread.sleep(500);
				} catch (Exception e) {}
            }
        }
    }

    private void start(ScanResult scanResult) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        xdata = new double[frequency];
        ydata = new double[frequency];
        lydata = new double[frequency];
        oydata = new double[frequency];
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
        	ll.setVisibility(LinearLayout.VISIBLE);
            //this.showProgressDialog(ctx, "正在进行CMCC-AUTO PEAP认证...", frequency);
            initTask(task, ctx, ConnectivityManager.TYPE_WIFI);
            task.startTime = StringUtils.getDateTime();
            final PeapTestThread peapThread = new PeapTestThread(scanResult);
            peapThread.start();
        }
    }
    TimerTask peapConnectTimerTask, peapDisconnectTimerTask;
    Timer timer;
    private void startConnectTimeoutListener() {
    	peapConnectTimerTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
                    wlanManager.sendMsg(MessageWhat.PEAP_FAILD_CONNECTED);
                }
            }
        };
        timer = new Timer();
        timer.schedule(peapConnectTimerTask, WlanManager.CONNECT_TIMEOUT);
    }
    private void startDisconnectTimeoutListener() {
    	peapDisconnectTimerTask = new TimerTask() {
            public void run() {
                if (connecting) {
                	wlanManager2.setConnectedConsumeTime(System.currentTimeMillis());
                	wlanManager2.sendMsg(MessageWhat.PEAP_FAILD_DISCONNECTED);
                }
            }
        };
        timer = new Timer();
        timer.schedule(peapDisconnectTimerTask, WlanManager.CONNECT_TIMEOUT);
    }
 
    void update(int what) {
    	try {
    		peapConnectTimerTask.cancel();
    	} catch(Exception e){}
    	try {
    		peapDisconnectTimerTask.cancel();
    	} catch(Exception e){}
    	pb.setProgress(current);
        switch (what) {
        case MessageWhat.PEAP_SUCESS_CONNECTED:
        	
            setDialogProgress(current);
            if (connecting) {
                float costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / (float)1000; 
                xdata[current - 1] = current;
                xdata[current - 1] = current-1;
                lydata[current - 1] = costTime;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次PEAP认证成功：");
                s.append(wlanManager.getCurrentScanResult().SSID).append("\nMAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append('\n');
                s.append("IP：").append(wlanManager.getIpAddress()).append(" 时间：");
                s.append(costTime).append(" s\n");
                totalTime += costTime;
                 /*  long costTime2 = (System.currentTimeMillis() - wlanManager.getConnectedConsumeTime()) / 1000;
                oydata[current - 1] = costTime2;
                s.append("第").append(current).append("次PEAP下线成功：");
                s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append('\n');
                s.append(" 时间：");
                s.append(costTime2).append(" s\n"); 
                totalDisTime += costTime2;*/
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv);
                connecting = false;
                isTestPeapConnect = 2;
            }
            break;
        case MessageWhat.PEAP_FAILD_CONNECTED:
        	setDialogProgress(current);
            if (connecting) {
            	setTimeoutNum(1);
                float costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / (float)1000; 
                xdata[current - 1] = current;
                xdata[current - 1] = current-1;
                lydata[current - 1] = costTime;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次PEAP认证：");
                s.append(wlanManager.getCurrentScanResult().SSID).append("\nMAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append("失败.\n");
                totalTime += costTime;
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv);
                connecting = false;
                isTestPeapConnect = 2;
            }
        	break;
        case MessageWhat.PEAP_SUCESS_DISCONNECTED:
            if (connecting) { 
                float costTime2 = (wlanManager2.getConnectedConsumeTime() - wlanManager2.getStartDisConntectTime()) / (float)1000;
                xdata[current - 1] = current-1;
                oydata[current - 1] = costTime2;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次PEAP下线成功：");
                s.append(wlanManager.getCurrentScanResult().SSID).append("\nMAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append('\n');
                s.append(" 时间：");
                s.append(costTime2).append(" s\n");
                totalDisTime += costTime2;
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv); 
                connecting = false;
                isTestPeapConnect = 1;
                if (current >= frequency) {
                	isTestPeapConnect = 0;
                	this.dismissProgressDialog();
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
            }
            break;
        case MessageWhat.PEAP_FAILD_DISCONNECTED:
        	if (connecting) { 
                float costTime2 = (wlanManager2.getConnectedConsumeTime() - wlanManager2.getStartDisConntectTime()) / (float)1000;
                xdata[current - 1] = current-1;
                oydata[current - 1] = costTime2;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次PEAP下线：");
                s.append(wlanManager.getCurrentScanResult().SSID).append("\nMAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append("失败");
                totalDisTime += costTime2;
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv); 
                connecting = false;
                isTestPeapConnect = 1;
                if (current >= frequency) {
                	isTestPeapConnect = 0;
                	this.dismissProgressDialog();
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
            }
        	break;
        /*case MessageWhat.WIFI_CONNECT_TIMEOUT:
            setDialogProgress(current);
            float costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / (float)1000; 
            xdata[current - 1] = current;
            xdata[current - 1] = current-1;
            lydata[current - 1] = costTime;
            totalTime += costTime;
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次PEAP认证：");
            s.append(wlanManager.getCurrentScanResult().SSID).append("\nMAC地址：");
            s.append(wlanManager.getCurrentScanResult().BSSID).append("失败.\n");
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            l.addView(tv);
            setTimeoutNum(1);
            setTimefailNum(1);
            connecting = false;
            if (current >= frequency) {
            	this.dismissProgressDialog();
                wlanManager.sendMsg(MessageWhat.DONE);
            }
            break;*/
        case MessageWhat.DONE:
        	tv_peap.setText("测试完成");
        	StringBuffer s = new StringBuffer();
            s = new StringBuffer();
            DecimalFormat df = new DecimalFormat("#0.000");
            int success = frequency - timeout_num;
            int dissuccess = frequency - timeDisFail_num;
            s.append("PEAP认证次数：").append(frequency).append('\n');
            s.append("PEAP认证成功次数：").append(success);
            s.append("  认证成功率：").append((float) success / frequency * 100).append('%').append('\n'); 
            s.append("PEAP认证平均时延：").append(df.format((float) ((totalTime+totalDisTime)/ frequency))).append('s');
            TextView tv = new TextView(ctx);
            tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.CYAN);
            tv.setText(s);
            l.addView(tv);
            drawChart();
            
            task.endTime = StringUtils.getDateTime();
            task.peapDelay = df.format((float) ((totalTime+totalDisTime) / frequency));
            task.peapSuccessRate = String.valueOf((float) success / frequency * 100);
            task.peapOffSuccessRate = String.valueOf((float) dissuccess / frequency * 100);
            
            connecting = false;
            executable = false;
            break;
        }
        setScrollViewDown(sv);

    }  
    private void drawChart() {
        chartLayout.removeAllViews();
        int max = getMax(lydata)>getMax(oydata) ? getMax(lydata):getMax(oydata);
        ChartManager cm = new ChartManager(ctx, 9, max);
        
        //ChartManager cm = new ChartManager(ctx, 8, 30);
        String chartTitle = "PEAP认证";
        String[] lineTitles = new String[] { "PEAP认证测试", "PEAP下线测试" };
        List<double[]> x = new ArrayList<double[]>(2);
        List<double[]> y = new ArrayList<double[]>(2);
        x.add(xdata);
        y.add(lydata);
        x.add(xdata);
        y.add(oydata);
        int[] colors = new int[] { Color.BLUE, Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        chartLayout.addView(lineChart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

        WlanManager wManager = new WlanManager(ctx);
        wManager.connect(scan);
        // 上传结果
      //  new UploadResultTask().execute();
    }
    private void setTimeoutNum(int timeout_num) {
        this.timeout_num += timeout_num;
    }
    private void setTimefailNum(int timeout_num) {
        this.timeFail_num += timeout_num;
    }

    private void setTimedisfailNum(int timeout_num) {
        this.timeDisFail_num += timeout_num;
    }
    
    private class UploadResultTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            showMessage(ctx, "正在上传结果...");
        }

        @Override
        protected String doInBackground(Void... params) {
            
            if (fileName == null) {
                TaskParser parser = new PullTaskParser();
                fileName = parser.XmlFileCreator(task);
            }
            if (uplod(fileName, ctx, handler)) {
                fileName = null;
            }
            return fileName;
        }
        /*
        protected void onPostExecute(String result) {
            if (result == null) {
                showMessage(ctx, "上传成功.");
            }
        }*/
    }
    //判断是否存在CMCC-AUTO扫描结果
    public final ScanResult retureCMCCAUTOScan(List<ScanResult> scanResults) {
        int length = scanResults.size();
        for (int i = 0; i < length;i++ ) { 
            ScanResult obj = scanResults.get(i);
            String ssid = obj.SSID;
            if(ssid!=null && ssid.equals(WlanManager.SSID_CMCC_AUTO)){
            	  //  if(ssid!=null && ssid.equals("TP-LINK_5908CC")){
            	return obj;
            }
        }
        return null;
    } 
    /**
     * 显示CMCC-AUTO扫描结果
     * @param ctx
     * @param wlanManager
     * @param handler
     */
    public void showCMCCAUTOScanDialog(Activity ctx, WlanManager wlanManager, final Handler handler) {
        final List<ScanResult> scanResults = wlanManager.getScanResults();
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        final ScanResult scanResult = this.retureCMCCAUTOScan(scanResults); 
        if(scanResult ==null ) 
        { 
        	builder.setTitle("CMCC-AUTO扫描错误");  
//        	builder.setIcon(R.drawable.what);
        	builder.setMessage("无条件进行CMCC-AUTO PEAP认证");
        	builder.setCancelable(false);
     		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
     			public void onClick(DialogInterface dialog, int id) {
                     Message msg = new Message();
     	             msg.what = MessageWhat.PEAP_NO_RESULT; 
               //  handler.sendMessage(msg);
     			}
     		}); 
     		wifiListDialog = builder.create();
            wifiListDialog.show();
        }else{ 
        	 scan = scanResult;
        	 Message msg = new Message();
        	 //直接使用cmcc账号
        	 DBManager db = new DBManager(ctx);
        	 Account config = db.getAccount();
        	 if (config !=null ) {
        		 wEapManager = new WifiEAPManager(ctx);
        		 wEapManager.removeEapConfig();
				 wEapManager.saveEapConfig(config.password, config.userName,"");
        		 msg.what = MessageWhat.WIFI_SELECTED;
        		 handler.sendMessage(msg);
			 }else {
				Toast.makeText(ctx, "请到系统管理账号配置中输入完整信息", Toast.LENGTH_LONG).show();
			}
//         	 if(!wlanManager.isExistConfig(WlanManager.SSID_CMCC_AUTO)){ 
//        		 msg.what = MessageWhat.PEAP_INPUT_AUTHINFO; 
//        	 }else {
//				 msg.what = MessageWhat.WIFI_SELECTED;
//			 }
//        	 handler.sendMessage(msg);
        }
		  
    }
    /**
     * 配置Peap认证是的身份、匿名身份和无线密码
     * @param ctx
     * @param wlanManager
     * @param handler
     */
    public void inputUserPassDialog(WlanManager wlanManager, final Handler handler) {
    	LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(R.layout.peap_input_user_pass_dialog, null);
		final EditText identText = (EditText) dialogView.findViewById(R.id.peapIdentity);
		final EditText anonIdentText = (EditText) dialogView.findViewById(R.id.peapAnonIdentity);
		final EditText passText = (EditText) dialogView.findViewById(R.id.peapPassword);
        final List<ScanResult> scanResults = wlanManager.getScanResults();
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        final ScanResult scanResult = this.retureCMCCAUTOScan(scanResults); 
        builder.setTitle("PEAP认证账号");   
        builder.setView(dialogView); 
        builder.setCancelable(false); 
        builder.setPositiveButton("配置", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int id) {
	       		 String identity = identText.getText().toString();
	    		 String anonident = anonIdentText.getText().toString();
	    		 String password = passText.getText().toString();
	    		 try { 
	    			 Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					 field.setAccessible(true);
	    			 if (StringUtils.isEmpty(identity)) {
						field.set(dialog, false);
						showMessage(ctx, "请输入身份");
					 }else if (StringUtils.isEmpty(password)) {
						field.set(dialog, false);
		    			showMessage(ctx, "请输入无线密码");
					 }else{ 
						 field.set(dialog, true);
						 wEapManager = new WifiEAPManager(ctx);
						 wEapManager.saveEapConfig(password, identity,anonident);
						 scan = scanResult;
			        	 Message msg = new Message();
			             msg.what = MessageWhat.WIFI_SELECTED; 
			             handler.sendMessage(msg);
					 }
	    		 } catch (Exception e) {
						e.printStackTrace();
						showMessage(ctx, "配置失败，请稍后重试");
				 }
        	}
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
        	public void onClick(DialogInterface dialog, int id) {
        		try {
					Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
        		dialog.cancel();
        	}
        });
	 	wifiListDialog = builder.create();
	    wifiListDialog.show(); 
    }
	public ScanResult getScan() {
		return scan;
	}

	public void setScan(ScanResult scan) {
		this.scan = scan;
	}

	public long getStartTime() {
		return startTime;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public long getEndTime() {
		return endTime;
	}

	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}
 
}
